import { login, logout, getMyPermissions, getMyInfo, getStationList, getMyCompanyInfo } from '@/api/user'
import { getStationListToolBar } from '@/api/station'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  myInfo: {},
  stationList: [],
  stationId: '',
  wiring: '',
  model: '',
  myCompanyInfo: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MYINFO: (state, myInfo) => {
    state.myInfo = myInfo
  },
  SET_STATIONLIST: (state, stationList) => {
    state.stationList = stationList
  },
  SET_STATIONId: (state, stationId) => {
    // state.stationList = stationList[0].id
    // console.log(stationId)
    state.stationId = stationId
  },
  SET_WIRING: (state, wiring) => {
    state.wiring = wiring
  },
  SET_MODEL: (state, model) => {
    state.model = model
  },
  SET_MYCOMPANYINFO: (state, myCompanyInfo) => {
    state.myCompanyInfo = myCompanyInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password: password }).then(response => {
        const { headers } = response
        commit('SET_TOKEN', headers['api-token'])
        setToken(headers['api-token'])
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getMyInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getMyInfo().then(response => {
        const { data } = response
        if (data.company_type === 'maintain') {
          commit('SET_NAME', data.company_name)
        }

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        commit('SET_MYINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户站点选择
  getStationList({ commit }) {
    return new Promise((resolve, reject) => {
      getStationList(this.state.user.myInfo.company_id).then(response => {
        const { data: { data }} = response
        commit('SET_STATIONLIST', data)
        commit('SET_STATIONId', data[0].id)
        commit('SET_WIRING', data[0].wiring)
        commit('SET_NAME', data[0].name)
        commit('SET_MODEL', data[0].model)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 运维站点选择
  getStationListToolBar({ commit }) {
    return new Promise((resolve, reject) => {
      getStationListToolBar().then(res => {
        console.log(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getMyCompanyInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getMyCompanyInfo(this.state.user.myInfo.company_id).then(response => {
        const { data } = response
        commit('SET_MYCOMPANYINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getMyPermissions({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMyPermissions(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        commit('SET_ROLES', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch, rootState }) {
    console.log(rootState.permission)
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_STATIONLIST', [])
        commit('SET_STATIONId', '')
        commit('SET_NAME', '')
        commit('SET_MODEL', '')
        commit('SET_MYINFO', {})
        commit('permission/SET_ROUTES', [], { root: true })
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_STATIONId', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
